﻿using XinLife.Application.Interface;
using XinLife.Common;
using XinLife.Core;
using XinLife.Model;
using XinLife.Model.Dto;
using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using XinLife.Core.Model;
using XinLife.Core.Helper;
using System.IO;

namespace XinLife.Controllers.Admin
{
    /// <summary>
    /// 菜单管理
    /// </summary>
    public class ModuleController : BaseController
    {
        IModuleService _moduleService;
        private readonly IWebHostEnvironment _webHostEnvironment;
        public ModuleController(IModuleService moduleService, IWebHostEnvironment webHostEnvironment)
        {
            _moduleService = moduleService;
            _webHostEnvironment = webHostEnvironment;
        }

        /// <summary>
        /// 获取功能模块列表
        /// </summary>
        [HttpGet]
        public async Task<object> GetModulePageList([FromQuery] Pagination pagination, [FromQuery] string queryJson = null)
        {
            return await _moduleService.GetModulePageListAsync(pagination, queryJson);
        }
        /// <summary>
        /// 获取所有父级的菜单
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<AjaxResult> GetParentIdModule()
        {
            var data= await _moduleService.GetParentIdModule();
            Func<List<Module>, string, List<object>> res = null;
            //递归0.0
            res = (List<Module> list, string parentId) =>
            {
                var items = list.FindAll(t => t.cParentId == parentId).OrderBy(t => t.cSortCode).ToList();

                var b = new List<object>();

                items.ForEach(t =>
                {
                    b.Add(new 
                    {
                        value = t.cId,
                        Icon = t.cIcon,
                        Name = t.cTitle,
                        Children = res(list, t.cId)
                    });
                });
                return b;
            };
            return Success(res(data.ToList(), "0"));
        }
        /// <summary>
        /// 获取菜单表单信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<AjaxResult> GetModuleById(string id)
        {
            return await _moduleService.GetModuleById(id);
        }
        /// <summary>
        /// 获取菜单按钮列表
        /// </summary>
        [HttpGet]
        public async Task<object> GetModuleButtonPageList([FromQuery] Pagination pagination, [FromQuery] string queryJson = null)
        {
            return await _moduleService.GetModuleButtonPageList(pagination, queryJson);
        }
        /// <summary>
        ///编辑菜单按钮
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<AjaxResult> EditModuleButton([FromForm] ModuleButton moduleButton)
        {
            return await _moduleService.EditModuleButton(moduleButton);
        }
        /// <summary>
        /// 获取菜单按钮表单信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<AjaxResult> GetModuleButtonById(string id)
        {
            return await _moduleService.GetModuleButtonById(id);
        }
        /// <summary>
        ///编辑模块
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<AjaxResult> EditModule([FromForm] Module module)
        {
            return await _moduleService.EditModuleAsync(module);
        }
        /// <summary>
        /// 删除按钮
        /// </summary>
        [HttpPost]
        public async Task<AjaxResult> DelModuleButton([FromForm] string ids)
        {
            return await _moduleService.DelModuleButton(ids);
        }
        /// <summary>
        /// 删除菜单
        /// </summary>
        [HttpPost]
        public async Task<AjaxResult> DelModule([FromForm] string ids)
        {
            return await _moduleService.DelModuleAsync(ids);
        }
        /// <summary>
        /// 获取用户菜单列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<AjaxResult> GetUserModuleList()
        {
            var data = await _moduleService.GetUserModule(AspNetUser.UserId);
            Func<List<Module>, string, List<ModuleOutputDto>> res = null;
            //递归0.0
            res = (List<Module> list, string parentid) =>
            {
                var items = list.FindAll(t => t.cParentId == parentid).OrderBy(t => t.cSortCode).ToList();

                var b = new List<ModuleOutputDto>();

                items.ForEach(t =>
                {
                    b.Add(new ModuleOutputDto()
                    {
                        Id = t.cId,
                        Title = t.cTitle,
                        Icon = t.cIcon,
                        Name = t.cTitle,
                        CompName = t.cName,
                        CompPath = t.cPath,
                        Path = t.cPath,
                        Children = res(list, t.cId)
                    });
                });
                return b;
            };
            return Success(res(data, "0"));
        }
        /// <summary>
        /// 获取模块所对应的角色
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<AjaxResult> GetModuleRoles([FromQuery] string moduleId, [FromQuery] string buttonIds)
        {
            return await _moduleService.GetModuleRoles(moduleId, buttonIds);
        }
        /// <summary>
        /// 获取选中的角色下的菜单下的共有按钮
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<AjaxResult> GetRoleModules([FromQuery] string moduleId, [FromQuery] string roleIds)
        {
            return await _moduleService.GetRoleModules(moduleId, roleIds);
        }
        

        /// <summary>
        /// 按钮 角色权限赋值
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<AjaxResult> ButtonsRoleAuth([FromForm] ButtonsAuthInputDto dto)
        {
            return await _moduleService.ButtonsRoleAuth(dto);
        }

        /// <summary>
        /// 获取网站目录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<AjaxResult> GetPageDir()
        {
            var wwwrootPath = _webHostEnvironment.WebRootPath;
            List<object> items = GetFileSystemItems(Path.Combine(wwwrootPath, "views"));
            return Success(items);
        }


        [NonAction]
        public List<object> GetFileSystemItems(string directoryPath)
        {
            List<object> items = new List<object>();
            DirectoryInfo directory = new DirectoryInfo(directoryPath);
            foreach (var fileInfo in directory.GetFiles())
            {
                items.Add(new
                {
                    Name = fileInfo.FullName.Substring(fileInfo.FullName.IndexOf("views")).Replace("\\", "/"),
                    IsDirectory = false,
                    Value= fileInfo.FullName.Substring(fileInfo.FullName.IndexOf("views")).Replace("\\", "/")
                });
            }
            foreach (var subDirectory in directory.GetDirectories())
            {
                items.Add(new
                {
                    Name = subDirectory.FullName.Substring(subDirectory.FullName.IndexOf("views")).Replace("\\", "/"),
                    IsDirectory = true,
                    Children = GetFileSystemItems(subDirectory.FullName),
                    Value = subDirectory.FullName.Substring(subDirectory.FullName.IndexOf("views")).Replace("\\", "/")
                });
            }
            return items;
        }
    }
}
